package com.ww.springboot.boot.thread.study.base.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo3 {


    Lock lock = new ReentrantLock();
    Condition conditionA = lock.newCondition();

    public void printA() {
        System.out.println("-------A入口------");
        //加锁
        lock.lock();
        try {
            System.out.println("-------A开始------");
            TimeUnit.SECONDS.sleep(3);
            //(await 会让出锁资源)
            conditionA.await();
            System.out.println("-------A结束------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            lock.unlock();
        }
    }

    public void printB() {
        System.out.println("-------B入口------");
        //加锁
        lock.lock();
        try {
            System.out.println("-------B开始------");
            TimeUnit.SECONDS.sleep(10);
            //(signal 唤醒await)
            conditionA.signal();
            System.out.println("-------B结束------");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 释放锁
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        LockDemo3 test = new LockDemo3();
        // 建立打印ABC的三个线程
        Thread theadA = new Thread(() -> {
            test.printA();
        });
        Thread theadB = new Thread(() -> {
            test.printB();
        });

        // 启动线程
        theadA.start();
        theadB.start();
    }
}